<?php

namespace app\model;

use App\user\cache\UserTokenCache;
use Illuminate\Database\Eloquent\SoftDeletes;
use support\Model;

class UserTokenModel extends Model
{

    protected $table = 'user_token';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $dateFormat = 'U';
    use SoftDeletes;
    const DELETED_AT = 'logout_time';
    protected $fillable = ['user_id', 'token', 'ip', 'login_time'];
    // 创建信息
    public static function createInfo($data) {
        $data['login_time'] = time();
        $list = self::where(['user_id' => $data['user_id']])->get()->toArray();
        $count = count($list);
        if ($count>=2) {
            self::deleteToken($data['user_id'], $count-1);
        };
        return self::create($data);
    }

    public static function updateToken($userId, $info) {
        $list = self::where(['user_id' => $userId])->select('token')->get();
        foreach ($list as $item) {
            UserTokenCache::set($item->token, $info, 7*24*3600);
        }
    }

    public static function deleteInfo($userId, $token) {
        return self::where(['user_id' => $userId, 'token' => $token])->delete();
    }

    public static function deleteToken($userId, $limit = null) {
        $deleteList = self::where(['user_id' => $userId])->select(['id', 'token'])->orderBy('login_time', 'asc')->limit($limit)->get();
        foreach ($deleteList as $item) {
            $res = $item->delete();
            UserTokenCache::del($item->token);
        }
    }
}